<?php
use Illuminate\Http\Request;

/**
 * Description of WechatController
 *
 * @author Administrator
 */
class Wechat {
    private $data;  //保存微信推送信息object
    private $token;
    /**
     * 对象初始化
     * @param Request $request
     */
    public function __construct(Request $request) {
        if($request->input('echostr')) {
            $this->wechatCheckSignature($request) || exit();
            echo $request->input('echostr');
            exit();
        } else {
            $this->wechatSetToken();
            $this->wechatSetData();
        }
    }
    
    protected function wechatSetToken() {
        $token = \App\Models\Token::getToken(1);
        if ($token['status'] == 1) {
            $this->token = $token['info'];
        } else {
            exit($token['info']);
        }
    }
    
    /**
     * 保存微信推送信息
     */
    protected function wechatSetData() {
        $postStr = @$GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->data = $postObj;
        } else {
            exit("没有收到任何信息");
        }
    }
    
    /**
     * 获取微信推送信息
     * @return type
     */
    public function wechatGetData() {
        return $this->data;
    }
    
    public function wechatGetToken() {
        return $this->token;
    }
    /**
     * 验证微信签名
     * @param Request $request
     * @return type
     * @throws Exception
     */
    private function wechatCheckSignature(Request $request) {
        if (!env('WECHAT_TOKEN')) {
            throw new Exception('TOKEN is not defined!');
        }
        $signature  = $request->input('signature');
        $timestamp  = $request->input("timestamp");
        $nonce      = $request->input('nonce');
        $token      = env('WECHAT_TOKEN');
        $tmpArr = [$token, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        return $tmpStr ==$signature;
    }
}